package edu.uwm.cs552;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class MoveDraw implements HexBoardEditAction {
	private final HexCoordinate move;
	private final Player player;
	private ImageIcon[] icons;

	public MoveDraw(HexCoordinate h, Player p) {
		move = h;
		player = p;
	}
	
	public HexCoordinate getMoveTrain() {
		return move;
	}
	
	public void apply(HexBoard hexBoard, Point p, double scale, double bound) {
		HexCoordinate h = HexCoordinate.fromPoint(p, scale);
		if (move == null) hexBoard.removeMove(player, h);
		else hexBoard.putMove(player, h, move);
	}
	
	public String getLabel() {
		return move == null ? "Clear Move" : "Move Train";
	}

	public ImageIcon getIcon() {
		int i = move == null ? 0 : 1;
		return getMoveIcons(player != null ? player.getPlayerColor() : Color.BLACK)[i];
	}

	/**
	 * Return the (singleton) array of icons for terrains indexed by terrain ordinal.
	 * With one extra item at the end for blank icon.
	 * @return
	 */
	private ImageIcon[] getMoveIcons(Color c) {
		if (icons == null) {
			ImageIcon[] result = new ImageIcon[2];
			for (int i=0; i < result.length; ++i) {
				BufferedImage im = new BufferedImage(MoveDraw.ICON_SIZE,MoveDraw.ICON_SIZE, BufferedImage.TYPE_INT_ARGB);
				Graphics g = im.getGraphics();
				g.translate(MoveDraw.ICON_SIZE/2, MoveDraw.ICON_SIZE/2);
				if (i > 0) {
					((Graphics2D)g).setColor(c);
					float alpha = 0.3f;
					int type = AlphaComposite.SRC_OVER; 
					AlphaComposite composite = AlphaComposite.getInstance(type, alpha);
					((Graphics2D)g).setComposite(composite);
					((Graphics2D)g).fillPolygon(HexCoordinate.ORIGIN.toPolygon(MoveDraw.ICON_SIZE));
				}
				result[i] = new ImageIcon(im);
			}
			icons = result;
		}
		return icons;
	}
}
